package com.asen.libcommon.util

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.PixelFormat
import android.graphics.drawable.Drawable

/**
 * @date   : 2020/12/11
 * @author : asenLiang
 * @e-mail : liangAisiSen@163.com
 * @desc   : Drawable图片处理工具
 */

object DrawableUtil {
    /**
     * drawable 转 bitmap
     *
     * @param drawable 要转换的Drawable
     * @return 转换完成的Bitmap
     */
    fun drawableToBitmap(drawable: Drawable): Bitmap {
        val w = drawable.intrinsicWidth
        val h = drawable.intrinsicHeight
        val config =
            if (drawable.opacity != PixelFormat.OPAQUE) Bitmap.Config.ARGB_8888 else Bitmap.Config.RGB_565
        val bitmap = Bitmap.createBitmap(w, h, config)
        //  注意，下面三行代码要用到，否则在View或者SurfaceView里的canvas.drawBitmap会看不到图
        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, w, h)
        drawable.draw(canvas)
        return bitmap
    }

    /**
     * 判断 Drawable 是否可用
     *
     * @param drawable true 可用  false 不可用
     * @return
     */
    fun drawableDisable(drawable: Drawable?): Boolean = drawable != null && drawable.intrinsicWidth > 0 && drawable.intrinsicHeight > 0

}